#include <iostream.h>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <semaphore.h>

int thread_flag;
pthread_cond_t thread_flag_cv;
pthread_mutex_t thread_flag_mutex;

void * thread_function(void * arg)
    {
    while (1)
        {
        pthread_mutex_lock(&thread_flag_mutex);
        while (!thread_flag)
            {
            cout << "thread_flag=" << thread_flag << endl;
            pthread_cond_wait(&thread_flag_cv, &thread_flag_mutex);
            }
        pthread_mutex_unlock(&thread_flag_mutex);

        cout << "Thread has been notified: thread_flag=" << thread_flag << endl;
        sleep(3);
        }

    return NULL;
    }

int main()
    {
    pthread_mutex_init(&thread_flag_mutex, NULL);
    pthread_cond_init(&thread_flag_cv, NULL);
    thread_flag = 0;

    pthread_t tid;

    pthread_create(&tid, NULL, thread_function, NULL);

    while (1)
        {
        pthread_mutex_lock(&thread_flag_mutex);
        thread_flag = !thread_flag;
        pthread_cond_signal(&thread_flag_cv);
        pthread_mutex_unlock(&thread_flag_mutex);

        sleep(2);
        }

    pthread_join(tid, NULL);

    return 0;
    }
